<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="title">校园绿植领养系统 - 管理后台</div>
      <el-form 
        :model="loginForm" 
        :rules="rules" 
        ref="formRef"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            prefix-icon="el-icon-user" 
            placeholder="用户名"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            prefix-icon="el-icon-lock" 
            type="password" 
            placeholder="密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { loginApi } from '@/api/auth';
import { useUserStore } from '@/store/user';

const router = useRouter();
const userStore = useUserStore();

const loginForm = reactive({
  username: '',
  password: ''
});

const formRef = ref(null);
const loading = ref(false);

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

const handleLogin = async () => {
  try {
    await new Promise((resolve) => {
      formRef.value.validate((valid) => {
        if (valid) resolve(true);
      });
    });

    loading.value = true;
    const res = await loginApi(loginForm);
    
    if (res.code === 200) {
      userStore.setToken(res.data.token);
      userStore.setUserInfo(res.data.user);
      router.push('/dashboard');
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #409eff 0%, #0a66c2 100%);
}

.login-card {
  width: 400px;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}
</style>